package _mst;

import java.util.ArrayList;
import java.util.List;

/**
 * 面试题 08.09. 括号
 */
public class T0809 {
    private List<String> ans;
    private StringBuilder path;
    private int n;

    public List<String> generateParenthesis(int n) {
        ans = new ArrayList<>();
        path = new StringBuilder();
        this.n = n;
        dfs(0, 0, 0);
        return ans;
    }

    private void dfs(int i, int l, int r) {
        if (i == n * 2) {
            ans.add(path.toString());
            return;
        }
        if (l < n) {
            path.append('(');
            dfs(i + 1, l + 1, r);
            path.deleteCharAt(i);
        }
        if (r < l) {
            path.append(')');
            dfs(i + 1, l, r + 1);
            path.deleteCharAt(i);
        }
    }
}
